<template>
  <el-scrollbar class="h-full">
    <el-form
      ref="formRef"
      v-loading="loading"
      :model="formState"
      :rules="rules"
      class="flex flex-col items-start gap-y-4"
      label-position="top"
      require-asterisk-position="right"
    >
      <QuoteCard header="域名配置">
        <div class="max-w-[400px] ml-2">
          <el-form-item class="mb-8" prop="openapi_addr">
            <template #label>
              <div class="text-black inline-block">API接口域名</div>
            </template>
            <small class="text-info block text-xs leading-[1.5] -mt-1 mb-3">
              配置API接口域名后，才能实现系统API开放能力，示例：http://dns.com
            </small>
            <el-input
              v-model.trim="formState.openapi_addr"
              maxlength="200"
              placeholder="请输入 http:// 或 https:// 开头的接口域名"
            ></el-input>
          </el-form-item>
          <el-form-item class="mb-8">
            <template #label>
              <div class="text-black inline-block">官网域名</div>
              <small class="text-info block text-xs leading-[1.5] mt-1 mb-3">
                用户端展示的官网域名信息，未填写则不展示
              </small>
            </template>
            <el-input
              v-model.trim="formState.website_addr"
              maxlength="200"
              placeholder="请输入官网域名"
            ></el-input>
          </el-form-item>
        </div>
        <div class="-ml-2">
          <el-divider />
          <el-button type="primary" @click="handleSave">保存配置</el-button>
        </div>
      </QuoteCard>
    </el-form>
  </el-scrollbar>
</template>

<script setup lang="ts">
import type { FormInstance, FormItemRule } from 'element-plus'

import { QuoteCard } from '@/components/application'
import ToastUtils from '@/utils/toast'

const formRef = ref<FormInstance>()
const loading = ref(false)
const formState = reactive({
  openapi_addr: '',
  website_addr: ''
})

const rules: Record<string, FormItemRule[]> = {
  openapi_addr: [
    {
      required: true,
      trigger: 'blur',
      pattern: /^(http|https):\/\/(.){1}/,
      message: '请输入 http:// 或 https:// 开头的接口域名'
    }
  ]
}

onMounted(() => {
  loading.value = true
  configInfoApi({})
    .then(res => {
      formState.openapi_addr = res.domain?.openapi_addr!
      formState.website_addr = res.domain?.website_addr!
    })
    .finally(() => {
      loading.value = false
    })
})

const handleSave = async () => {
  await formRef.value?.validate()
  loading.value = true
  try {
    await editConfigApi({ domain: formState })
    ToastUtils.success('修改成功')
  } finally {
    loading.value = false
  }
}
</script>
